package com.atguigu.gulimall.order.web;

import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutionException;

/**
 * @Author ShiJieLin
 * @Date 2022/4/29 21:05
 * @Version 1.0
 */
@Controller
public class OrderWebController {

    @Resource
    private OrderService orderService;

    /**
     * 用户在购物车点击结算，跳转结算页面，查询相关数据
     * 1. 会员的收货地址列表
     * 2. 在购物车中选中的商品
     * 3. 商品数量，总价，实际支付价格
     * @param model
     * @return
     */
    @GetMapping(value = "/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = orderService.confirmOrder();
        request.getSession();
        model.addAttribute("confirmOrderData", confirmVo);
        //展示订单确认的数据
        return "confirm";
    }

    /**
     * 用户点击提交订单，生成对应的支付页面
     * @param vo         订单信息
     * @param model
     * @param attributes
     * @return
     */
    @PostMapping(value = "/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes attributes) {
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            // 1.表示下单成功，返回到支付页面
            if (null != responseVo && responseVo.getCode() == 0) {
                model.addAttribute("submitOrderResp", responseVo);
                return "pay";
            } else {
                String msg = "下单失败";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "令牌订单信息过期，请刷新再次提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "库存锁定失败，商品库存不足";
                        break;
                }
                attributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            // 库存如果不够
            attributes.addFlashAttribute("msg", e);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

}
